<template>
  <div class="content">
    <FilterTable
      ref="packageWxlj"
      :maxHeight="500"
      :columns="columns"
      :dataSource="dataSource"
      :isColumnFilter="false"
      :isSelectColumn="packageType !== 'look'"
      :isToperInfo="false"
      :columnsRef="$route.path + 'packageMaintenanceDLR-wxlj'"
      :onCellChange="onCellChange"
      :onSyncTableData="onSyncTableData"
      :onRowSelectChange="selectChange"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <!-- <template slot="controls" slot-scope="props">
        <div style="text-align: right; margin-bottom: 10px">
          <el-button type="text" :disabled="disabledType" icon="iconfont icon-add" @click="add">新增</el-button>
          <el-button type="text" :disabled="isDeleted" @click="deletePart"><i class="el-icon-delete"></i>删除</el-button>
        </div>
      </template> -->
    </FilterTable>
    <BaseDialog :visible.sync="visiblePeij" title="备件选择" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <addPeij :status="1" @selectArr="selectPeijFun" @closeVin="closeDialog"></addPeij>
    </BaseDialog>
  </div>
</template>

<script>
// import _ from 'lodash';
import { dictionary } from '@/utils/dictMixin';
import addPeij from './addPeij.vue';
import { state, mutations } from '../store';
// import addWxlj from '@/pages/server/businessSetting/packageMaintenanceDLR/children/addWxlj.vue';
import { checkDiscount } from '@/utils/validate';
// import { getStroageList } from '@/api-server/part/partOutbound/partBreak';
// import { getPayOrgInfo } from '@/api-server/public/index';
// import { getVaildAccountTypes } from '@/api-server/repair/repairReception/customer/history';
export default {
  name: 'wxlj',
  mixins: [dictionary],
  components: {
    addPeij
    // typeList
  },
  data() {
    return {
      roLabourIdList: [{ text: '', value: '' }],
      addWxlj: false, // 弹框开关
      visiblePeij:false,
      data: '',
      dataSource: [],
      editDataSource: [],
      columns: this.createTableColumns(),
      formList: this.createFormList(),
      selectRows: [],
      disabledType: true,
      isLdc: '',
      totalData: [], // 维修类型和账类下拉数据总和
      jxxmEditItems: [], // 交修项目
      showTypeList: false, // 账类说明
      isDeleted: true,
      orgList: [],
      peijArr:[],
      storageList: [], // 仓库列表
      modelCode: null,
      isLdcData: '',
      sportArr:[],
      priceList: ['partCostPrice', 'costPrice', 'claimPrice', 'instructPrice', 'planPrice', 'latestPrice']
    };
  },
  computed: {
    packageType() {
      return state.packageType;
    },
    packageAllMoney() {
      return state.packageAllMoney;
    },
    packageWxgsList() {
      return state.packageWxgsList;
    },
    packageWxljList() {
      return state.packageWxljList;
    }
  },
  watch: {
    // packageWxgsList(newValue, oldValue) {
    //   // console.log(newValue, 'watch---packageWxgsList---lj--');
    //   // if (!newValue || !newValue.length) {
    //   //   this.roLabourIdList = [];
    //   //   return;
    //   // }
    //   // this.roLabourIdList = newValue.map(x => ({ text: x.labourName, value: x.uuid }));
    //   // this.dataSource = [...this.dataSource];
    // },
    packageWxljList(newVal) {
      console.log(newVal, this.packageType, 'watch---packageWxljList---lj--');
      if (this.packageType !== 'add' && !this.dataSource.length) {
        this.dataSource = newVal;
        // this.baseTable.EXECUTE_INSERT(newVal);
        // this.dataSource = [...this.dataSource];
      }
      console.log(this.dataSource, 'packageWxljList--dataSource');
    }
  },
  async mounted() {
    this.baseTable = this.$refs.packageWxlj.$refs.pageTable;
    this.getStorage();
    this.getData();
    // const accountsTypeAll = await getVaildAccountTypes();
  },
  beforeDestroy() {},
  methods: {
   closeDialog() {
      console.log('关闭');
      this.visiblePeij = false;
    },
   /*配件 */
    async selectPeijFun(arr) {
      this.closeDialog();

      if (this.status == 1) {
        /*表单选择*/
        console.log('表单');
        this.formList.find((item) => item.fieldName == 'partNo').initialValue = arr[0].partNo;
        this.formList.find((item) => item.fieldName == 'partName').initialValue = arr[0].partName;
        this.formList.find((item) => item.fieldName == 'partSalesPrice').initialValue = arr[0].partSalesPrice;

        let params = {};
        params.addId = getAppId();
        params.bjxmbh = arr[0].partNo;
        this.rowDate.partNo = arr[0].partNo;
      } else {
        console.log('新建配件');
      }
      let newArr = [];
      arr.forEach((item, index) => {
        var pos = this.peijArr.findIndex((value, index, arr) => {
          if (value['partNo'] == item['partNo']) {
            /*如果存在则更新数量*/
            if (!isEmpty(item['amount'])) {
              value['amount'] = item['amount'];
            }
            if (!isEmpty(item['counts'])) {
              value['counts'] = item['counts'];
            }
          }
          return value['partNo'] == item['partNo'];
        });
        if (pos == -1) {
          newArr.push(item);
        }
      });

      this.baseTable.EXECUTE_INSERT(newArr);

      // this.dataSource = [...this.dataSource];
      // mutations.setPackageWxljList( this.dataSource);
      // this.BasePeijTable.DO_REFRESH();
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '折扣率',
          fieldName: 'discount',
          initialValue: 1,
          placeholder: '请输入...',
          disabled: true,
          maxlength: 4,
          onEnter: val => {
            this.handleDiscount(val);
            return;
          },
          change: val => {
            this.handleDiscount(val);
            return;
          },

          rules: [
            // { min: 0, max: 4, message: '只能输入两位小数', trigger: 'blur' },
            { validator: checkDiscount, trigger: 'blur' }
          ]
        }
      ];
    },

    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '备件代码',
          dataIndex: 'partNo',
          showOverflowTooltip: true,
          minWidth: 120
        },
        {
          title: '备件名称',
          dataIndex: 'partName',
          minWidth: 120,
          showOverflowTooltip: true
        },
        {
          title: '单位',
          dataIndex: 'unit',
          minWidth: 120,
          showOverflowTooltip: true
        },
        {
          editRequired: true,
          title:  '备件数量',
          dataIndex: 'partQuantity',
          minWidth: 100,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'number',
          initialValue: 1,
          min: 0,
          render: params => {
            return (
              <el-input
                disabled={this.packageType === 'look'}
                maxlength={8}
                min={0}
                value={params.row.partQuantity}
                onChange={e => {
                   if(Number(e)<0){
                        this.$notify.warning({ title: '提示信息', message: '备件数量不能小于0!' });
                    }
                    if(e.length>8){
                        this.$notify.warning({ title: '提示信息', message: '长度不能大于5!' });
                    }
                  params.row.partQuantity = e;
                  this.handleJhH(params.row);
                  mutations.setPackageWxljList(this.dataSource);
                }}
                v-model={params.row.partQuantity}
              >

              </el-input>
            );
          }
        },
        {
          editRequired: true,
          title:  '备件单价',
          dataIndex: 'partSalesPrice',
          minWidth: 150,
          precision: 2,
          editable: true,
          initialValue: 0.00,
          defaultEditable: true,
          editType: 'number',
          render: params => {
            // const list = this.setLabourPrice(params.row);
            return (
              <el-input
                disabled={this.packageType === 'look'}
                maxlength={8}
                min={0}
                // value={params.row.partSalesPrice}
                onChange={e => {
                  console.log('e',e)
                  if(Number(e)<0){
                    this.$notify.warning({ title: '提示信息', message: '备件单价不能小于0!' });
                  }
                  if(e.length>8){
                    this.$notify.warning({ title: '提示信息', message: '长度不能大于5!' });
                  }
                  params.row.partSalesPrice = e;
                  this.handleJhH(params.row);
                  mutations.setPackageWxljList(this.dataSource);
                }}
                v-model={params.row.partSalesPrice}
              >
              </el-input>
            );
          }
        },
        {
          title:  '备件费',
          dataIndex: 'partSalesAmount',
          // align: 'right',
          minWidth: 150,
          initialValue: 0.00,
          max:14,
          render: props => {
            console.log('props',props)
            return <span>{(props.row.partQuantity * props.row.partSalesPrice).toFixed(2)}</span>
          }
        },


         {
          title: '关联维修工时',
          dataIndex: 'relationLabourId',
          sorter: true,
          editType: 'select',
          editRequired: true,
          // editItems: this.packageWxgsList,
          initialValue: '请选择',
          render: (props) => {

                console.log('this=======', props.row.relationLabourId, this.packageWxgsList);

            return (
              <div>
                <el-select
                 disabled={this.packageType === 'look'}
                value={props.row.relationLabourId}  placeholder="请选择"  onChange={e => {
                  props.row.relationLabourId = e;
                }}
                clearable>

                  {this.packageWxgsList.map((item) => (
                    <el-option key={item.labourId} label={item.labourName} value={item.labourId} />
                  ))}
                </el-select>
              </div>
            );
          },
          max:14,

        },


      ];
    },
    giveValue(i) {
      i.repairTypeCode = this.formObject.repairCategoryCode;
      console.log(i.repairTypeCode, this.formObject.repairCategoryCode);
      let arr = [];
      arr = this.selectFilter(i.repairTypeCode);
      console.log(arr, 'arr-----');
      if (arr && arr.length && !i.isGiveValue) {
        console.log(arr, 'arr-----');
        i.accountsType = arr[0].chargePartitionCode;
        i.isGiveValue = true;
      }
      this.partSalesPriceChange(i);
      // let typeList = this.selectTypeId(i.accountsType, i.repairTypeCode);
      // if (typeList.length) {
      //   i.typeId = typeList[0].typeId;
      // }
    },
    handleDiscount(val) {
      const reg = /^[0-9]+([.]{1}[0-9]+){0,1}$/;
      if (!reg.test(val) || !Number(val) || Number(val) > 1 || val.length > 4) {
        // console.log('handleDiscount 格式不对');
        return;
      }
      if (this.selectRows.length) {
        this.selectRows.forEach(item => {
          if (item.accountsType + '' === '3') {
            item.discount = val;
            item.bookingQuantity = item.bookingQuantity ? Number(item.bookingQuantity) : 0;
            item.discount = item.discount ? Number(item.discount) : 1;
            item.partSalesPrice = item.partSalesPrice ? Number(item.partSalesPrice).toFixed(2) : 0;
            // item.partSalesAmount = Number(item.partSalesPrice * item.bookingQuantity).toFixed(2);
            item.receiveAmount = Number(item.partSalesPrice * item.bookingQuantity * item.discount).toFixed(2);
          }
        });
        this.dataSource = [...this.dataSource];
      }
    },
    add() {
      // 新增
      this.visiblePeij = true;

    },
    // 行选中
    selectChange(val) {
      this.selectRows = val;
    },
    // 删除' + this.$partsName + ',具体逻辑
    deleteClick() {
      console.log(2222222);
      if (!this.selectRows.length) {
        this.$notify.warning({ title: '提示信息', message: '请选择要删除的数据!' });
        return;
      }
      this.baseTable.EXECUTE_DELETE(this.selectRows);
      this.dataSource = [...this.dataSource];
      mutations.setPackageWxljList(this.dataSource);

    },
    // 同步表格数据
    onSyncTableData(val) {
      this.peijArr = val;
      console.log(val[0].partSalesAmount,val[0].partSalesPrice,val[0].partQuantity, 'onSyncTableData');

      let m = 0;
      let j = 0;
      // const idTag = false;
      for (const i of val) {
        m = m + (i.partSalesPrice ? Number(i.partSalesPrice) : 0) * (i.partQuantity ? Number(i.partQuantity) : 0);
        j += i.manufacturerBonus ? Number(i.manufacturerBonus) : 0;

      }
      // if (idTag) {
        mutations.setPackageWxljList(val);
      // }
      console.log(m);
      mutations.setAllMoney({ gs: this.packageAllMoney.gs, lj: m, fj: this.packageAllMoney.fj,jl: j,gl:this.packageAllMoney.gl,fl:this.packageAllMoney.fl });


    },
    createUidKey(key = '') {
      // 创建UID
      if (key !== '') {
        key += '-';
      }
      const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
      return key + uuid;
    },
    onCellChange(change, row) {
      // 判断
      console.log(change, row, 'onCellChange--');
      const key = Object.keys(change)[0];
      const name = key.substring(key.indexOf('|') + 1);
      // if (row.rowKey === 'S') {
      //   row.rowKey = 'U';
      // }

      this.dataSource = [...this.dataSource];
      mutations.setPackageWxljList(this.dataSource);
      let m = 0;
      if (m !== this.packageAllMoney.lj) {
        mutations.setAllMoney({ gs: this.packageAllMoney.gs, lj: m, fj: this.packageAllMoney.fj,jl:this.packageAllMoney.jl });

      }
    },
    edit() {
      // 编辑
    },

    // 服务套餐带入维修' + this.$partsName + '
    async saveFwtcPart(fwtcArray) {
      const partArray = [];
      fwtcArray.forEach(x => {
        x.partList.forEach(y => {
          partArray.push(y);
        });
      });
      console.log(partArray,  '备件数组');
      // let val = await findAllRepair();
      // let ldcPart = val.data['4005'];
      partArray.forEach(x => {
        x.functionGroup = x.functionCode;
        x.productGroup = x.productKind;
        x.isObligated = 10041002;
        x.bookingQuantity = x.partQuantity;
        // x.ldcPart = this.isLdcData == '82591002' ? 10041001 : 10041002;
        x.repairTypeCode = this.formObject.repairCategoryCode;
        if (x.repairTypeCode) {
          const arr = this.selectFilter(x.repairTypeCode);
          if (arr && arr.length) {
            console.log(arr, 'arr-----');
            x.accountsType = arr[0].chargePartitionCode;
          }
          // let typeList = this.selectTypeId(x.accountsType, x.repairTypeCode);
          // if (typeList.length) {
          //   x.typeId = typeList[0].typeId;
          // }
        }

        this.saveHandle(x);
      });

      this.$nextTick(() => {
        // 服务套餐' + this.$partsName + ',交修序号置灰
        this.dataSource.forEach(x => {
          if (x.setCode) {
            // this.$refs.table.SET_CELL_DISABLED(x, 'jobNo', true);
            this.$refs.table.SET_CELL_DISABLED(x, 'bookingQuantity', true);
          }
        });
      });
    },

    // 新增的数据保存
    saveHandle(obj) {
      console.log(obj, 'saveHandle==');
      if (!obj) {
        return;
      }
      // ' + this.$partsName + '判重
      const flag = this.dataSource.find(x => x.partNo === obj.partNo);
      if (flag) {
        this.$notify.warning({ title: '提示信息', message: '不能重复添加！' });
        return;
      }

      // this.addWxlj = false;
      const data = JSON.parse(JSON.stringify(obj));
      data.rowKey = 'A';
      data.discount = 1;
      data.partQuantity = data.minPackage;
      data.sortNum = null;
      data.groupLevel = null;
      this.handleJhH(data);
      this.baseTable.EXECUTE_INSERT(data);
      this.dataSource = [...this.dataSource];
      this.$notify.success({ title: '提示信息', message: '添加成功!' });
      mutations.setPackageWxljList(this.dataSource);

      console.log(this.dataSource, '------wxlj');
    },

    closeDrawer() {
      // 弹框关闭
      this.visiblePeij = false;
    },
    // 获取仓库
    async getStorage() {
    },
    bookingQuantityFn(row) {
      console.log(row, 'bookingQuantityFn');
      row.bookingQuantity = row.bookingQuantity ? Number(row.bookingQuantity) : 0;
      row.discount = row.discount ? Number(row.discount) : 1;
      row.partSalesPrice = row.partSalesPrice ? Number(row.partSalesPrice).toFixed(2) : 0;
      // row.partSalesAmount = Number(row.partSalesPrice * row.bookingQuantity).toFixed(2);
      row.receiveAmount = Number(row.partSalesPrice * row.bookingQuantity * row.discount).toFixed(2);
      console.log(row, 'bookingQuantityFn');
      this.dataSource = [...this.dataSource];
    },
    // jobNo值改变
    jobNoChange(row) {
      // 选择jobno change事件
      this.jxxmList.forEach(x => {
        if (x.jobNo === row.jobNo) {
          row.repairTypeCode = x.repairTypeCode;
          this.columns.find(x => x.dataIndex === 'accountsType').editItems = this.selectFilter(this.repairCategoryCode).forEach(x => ({ text: x.chargePartitionName, value: x.chargePartitionCode }));
          row.accountsType = x.accountsType;
          this.partSalesPriceChange(row);
        }
      });
    },
    // 计算行改变的金额方法
    handleJhH(data) {
      // partQuantity' + this.$partsName + '数量  价格系数 priceRate   partSalesPrice销售单价  partSalesAmount 销售金额 discount折扣率 discountAmount 优惠金额 receiveAmount实收金额

      data.partQuantity = data.partQuantity ? Number(data.partQuantity).toFixed(2)  : 0;
      data.partSalesPrice = data.partSalesPrice ? Number(data.partSalesPrice).toFixed(2) : 0;
      data.manufacturerBonus = data.manufacturerBonus ? Number(data.manufacturerBonus).toFixed(2) : 0;

      console.log("handleJhH-data.partSalesPrice==",data.partSalesPrice);
      data.partSalesAmount = (data.partQuantity * data.partSalesPrice).toFixed(2);


    },
    // 金额计算
    partSalesPriceChange(row, type) {
      if (!row.accountsType) {
        // // console.log("partSalesPriceChange-价格归零");
        row.partSalesPrice = 0;
        this.handleJhH(row);
        return;
      }
      this.priceList.forEach(x => {
        row[x] = row[x] ? Number(row[x]) : 0;
      });
      if (type !== 'closeEditDrawer') {
        // 新的账类---》  2 索赔   3 自费  4 内结  5 权益  8保险
        if (row.accountsType + '' === '3' || row.accountsType + '' === '8') {
          row.partSalesPrice = row.instructPrice; // 建议销售价 tm_part_info.INSTRUCT_PRICE
        } else if (row.accountsType + '' === '2' || row.accountsType + '' === '5') {
          row.partSalesPrice = row.claimPrice; // 索赔价 tm_part_info.CLAIM_PRICE
        } else if (row.accountsType + '' === '4') {
          row.partSalesPrice = row.costPrice; // 含税成本价 tm_part_stock.cost_price
        } else {
          row.partSalesPrice = 0;
        }
      }

      row.partSalesPrice = Number(row.partSalesPrice).toFixed(2);
      this.handleJhH(row);
    },
    priceTypeChangeFn(row) {
      this.priceList.forEach(x => {
        if (!row[x]) row[x] = 0;
      });
      switch (row.priceType) {
        case 80501001:
          row.partSalesPrice = Number(row.partCostPrice).toFixed(2);
          break;
        case 80501006:
          row.partSalesPrice = Number(row.costPrice).toFixed(2);
          break;
        case 80501003:
          row.partSalesPrice = Number(row.claimPrice).toFixed(2);
          break;
        case 80501008:
          row.partSalesPrice = Number(row.instructPrice).toFixed(2);
          break;
        case 80501005:
          row.partSalesPrice = Number(row.latestPrice).toFixed(2);
          break;
        default:
          row.partSalesPrice = 0;
      }
    },
    // 账类的下拉框过滤
    selectFilter(val) {
      if (val) {
        return this.totalData.filter(x => x.repairTypeCode === val);
      } else {
        return [];
      }
    },
    // 账类说明的下拉框数据
    // selectTypeId(accountsType, repairTypeCode) {
    //   let typeOption = [];
    //   if (repairTypeCode == 'P') {
    //     typeOption.push(this.typeIdList[12]);
    //     return typeOption;
    //   }
    //   // 内结
    //   if (accountsType == 4) {
    //     return typeOption.concat(this.typeIdList);
    //   }
    //   if (accountsType != 9) {
    //     typeOption.push(this.typeIdList[0]);
    //     console.log(typeOption, 'typeOption');
    //     return typeOption;
    //   }
    // },
    // 获取初始账类数据
    async getData() {
      // const res = await getRepairTypeInfo();
      // if (res.data) {
      //   res.data.forEach(x => {
      //     this.totalData = this.totalData.concat(x.chargePartitionVoList);
      //   });
      // }
    },
    //  付款部门
    async getOrgsTree() {
      const res = await getPayOrgInfo();
      console.log(res, '付款部门res');
      this.orgList = res.data.map(x => ({ text: x.orgName, value: +x.orgId }));
      this.columns.find(x => x.dataIndex === 'pqymentDepartmentId').editItems = res.data.map(x => ({ text: x.orgName, value: +x.orgId }));
    }
  }
};
</script>

<style lang="less" scoped></style>
